<?php
declare (strict_types=1);

namespace app\service;

use app\model\SysDept;
use app\MyException;
use think\facade\Db;
use app\model\BaseModel;

/**
 * 部门
 * Class SysDeptUpdateService
 * @package app\service
 */
class SysDeptUpdateService
{

    /**
     * 部门列表
     * @param array $param 参数数组
     * @return json
     */
    public static function getSysDeptList($param)
    {
        $where = 'sd1.is_del = 0 ';
        if (!empty($param['condition'])) {
            $where .= ' and sd1.dept_name like "%' . $param['condition']['dept_name'] . '%"';
        }
        $res = SysDept::alias('sd1')->leftJoin('sys_dept sd2', 'sd1.parent_id = sd2.id')
            ->field('sd1.id,sd1.dept_name as deptName,sd1.parent_id as parentId,sd2.dept_name as parentDeptName,sd1.sort_no as sortNo')
            ->where($where)
            ->paginate(['page' => $param['page'], 'list_rows' => $param['pageSize']])->toArray();

        if (empty($res)) {
            return json_ok((object)array(), 0);
        }
        $list = ['total' => $res['total'], 'currentPage' => $res['current_page'], 'lastPage' => $res['last_page'], 'data' => $res['data']];
        return json_ok(formatData($list), 200);

    }

    /**
     * 部门新增、修改
     * @param array $param 参数数组
     * @return json
     */
    public static function addOrUpdate($data)
    {
        $deptId = $data['dept_id'] ?? 0;

        BaseModel::beginTrans();
        if ($deptId == 0) {//新增
            $oneDept = SysDept::where('is_del=0 and dept_name=:dept_name', ['dept_name' => $data['dept_name']])->find();
            if (!empty($oneDept)) {
                throw new MyException(10016);
            }
            try {
                $oneDept = new SysDept();
                $data['unit_id'] = '';
                $data['update_by'] = '';
                $data['enable'] = 1;
                $oneDept->allowField(['unit_id', 'dept_name', 'parent_id', 'sort_no', 'create_by', 'update_by', 'enable'])->save($data);
            } catch (\Exception $e) {
                BaseModel::rollbackTrans();
                throw new MyException(10005, $e->getMessage());
            }
        } else { //编辑
            $oneDept = SysDept::where('id=:id', ['id' => $deptId])->find();
            if (empty($oneDept)) {
                throw new MyException(10004);
            }

            $data['update_by'] = $data['create_by'];
            try {
                $oneDept->allowField(['unit_id', 'dept_name', 'parent_id', 'sort_no', 'create_by', 'update_by', 'enable'])->save($data);
            } catch (\Exception $e) {
                BaseModel::rollbackTrans();
                throw new MyException(10001, $e->getMessage());
            }
        }

        BaseModel::commitTrans();
        return json_ok((object)array(), 200);
    }

    /**
     * 部门详情
     * @param string $sysUserId 账户ID
     * @return json
     */
    public static function sysDeptDetails($deptId)
    {

        $res = SysDept::alias('sd1')->leftJoin('sys_dept sd2', 'sd2.parent_id = sd1.id')
            ->where('sd1.id=:id', ['id' => $deptId])
            ->field('sd1.id,sd1.dept_name as deptName,sd2.dept_name as parentDeptName,sd1.sort_no as sortNo')
            ->find();
        if (empty($res)) {
            return json_ok((object)array(), 0);
        }
        return json_ok($res, 200);

    }

    /**
     * 部门删除
     * @param string $sysUserId 账户ID
     * @return json
     */
    public static function sysDeptDelete($deptId)
    {

        BaseModel::beginTrans();
        try {

            if (strpos($deptId, ',') !== false) {
                $sysDeptIdArr = explode(',', $deptId);
                foreach ($sysDeptIdArr as $k => $v) {
                    $list[$k]['id'] = $v;
                    $list[$k]['is_del'] = 1;
                }
                $deptM = new SysDept;
                $deptM->saveAll($list);
            } else {
                $oneDept = SysDept::where('id=:id', ['id' => $deptId])->find();
                $oneDept->is_del = 1;
                $oneDept->save();
            }
        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            return json_error(100, $e->getMessage());
        }
        BaseModel::commitTrans();
        return json_ok((object)array(), 200);

    }

    /**
     * 获取所有部门
     */
    public static function getAllDept()
    {
        $res = SysDept::where('is_del', 0)->column('dept_name', 'id');
        if (empty($res)) {
            return json_ok((object)array(), 0);
        }
        return json_ok($res, 200);
    }
}
